<?php
/** 票付通对外接口入口地址 目前只有厦门开发组在用
 * Created by PhpStorm.
 * User: KaZeline
 * Date: 15-10-13
 * Time: 下午3:26
 */


/*
 *  1.接口访问方式为http REST方式实现。接口用post方式请求。
    2.加密验证参数sign为其他所有参数以字母顺序从a->z,组成key1=val1&key2=val2&...的形式后,再进行md5加密.
    例:某API参数为array('time'=>'2015-10-13','mid'=>1、'name'=>'example',则$sign=md5
(mid=1&name=example&time=2015-10-13).
    3.返回的数据解压方式为 json_decode(base64_decode($return)).
    4.所有API必传帐号(ac)密码(pw)参数,以下接口说明中将不再说明.
    5.带*号的参数为非必需参数
 */

//验证发送参数
if(!$_POST['ac'] || !$_POST['pw'] || !$_POST['sign'] || !$_POST['action']) response(102);
ksort($_POST);
$sign = $_POST['sign'];
unset($_POST['sign']);
$query_str = http_build_query($_POST);
if(md5($query_str) != $sign)  response(102);


$_POST['pw'] = md5($_POST['pw']);
//file_put_contents('/var/www/html/new/d/logs/api_user_api/log1.txt',
//    "\n".json_encode(array_merge(array('request_time'=>date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']),'remote_addr'=>$_SERVER['REMOTE_ADDR']),$_POST)),FILE_APPEND);



/*
$sql = "select id from pft_member where account=? and password=? limit 1";
$stmt = $connect->prepare($sql);
$stmt->execute(array($_POST['ac'],$_POST['pw']));
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
if(!$row['id'])
*/
if($_POST['ac']!='xiamenpiaofutong' || $_POST['pw'] !='c880abf353a87e5d9bccb15b6cfe52e6')
    response(101);

//如果上次访问日期不是今天 则重置访问次数 否则+1
/*
$today = date('Y-m-d');
if($row[0]['time']>=2000 && date('Y-m-d',$_SERVER['REQUEST_TIME'])==$row[0]['last_date']) response(110);
$sql = "update pft_api_account set time=time+1 ";
if(date('Y-m-d')>$row[0]['last_date']) $sql = "update pft_api_account set time=1,last_date='$today'";
$sql .= "where ac=? and pw=? limit 1";
$stmt->prepare($sql);
$stmt->excute(array($_POST['ac'],$_POST['pw']));
*/
use \PFT\Db;
use \pft\Member\MemberAccount;
include_once '/var/www/html/new/d/common/func.inc.php';
include_once '/var/www/html/new/d/class/MemberAccount.class.php';
include_once '/var/www/html/new/d/module/common/Db.class.php';
$dbConf = include_once '/var/www/html/new/d/module/common/db.conf.php';// 远端服务器配置信息
Db::Conf($dbConf['localhost']);


if(in_array($_POST['action'],array('Lands','Prods','SalePros','ResetPassword'/*,'ThemeProdList','SaleCity'*/))){
    include_once('/var/www/html/new/com.inc.php');
    include_once('/var/www/html/new/d/class/Member.php');
    include_once('/var/www/html/new/d/class/abc/Member.class.php');
    include_once("/var/www/html/new/d/class/abc/Product.class.php");
    //include_once('/var/www/html/new/d/class/abc/PFTCoreAPI.class.php');

}

if(in_array($_POST['action'],array('CouponList','collection_list','ShopCoupons','CollectCoupon','collect_detail'))){
    if($_POST['fid']+0==0 || $_POST['aid']+0==0) response(103);
    define('CLASS_PATH', '/var/www/html/new/d/class/');
    include '/var/www/html/new/com.inc.php';
    include CLASS_PATH . 'Api.class.php';
    include CLASS_PATH . 'Coupon.class.php';
    $coupon = new \PFT\Coupon($_POST['fid'], $_POST['aid']);
}


//表 pft_api_account  记录使用接口的各个用户的信息
/* 暂定字段
 * ac
 * pw
 * time 每天请求次数 超过两千次禁止再请求
 * last_date最后请求日期
 * */
$connect = Db::connect();
$s = new SoapClient(null,array(
        "location" => "http://localhost/open/openService/pft_insideMX.php",
        "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true")
);
$action = $_POST['action'];
switch ($_POST['action']) {
    //会员信息
    case 'MemberInfo':
        //fid和account至少要传一个
        if(!($_POST['fid']+0)) /*&&!($_POST['account']+0)) || !$_POST['password'] )*/ response(103);
        check_fx($_POST['fid']);
        $query = array();
//        $query = array(md5($_POST['password']));
//        if($_POST['fid']+0) {
            $where .= " and id=? ";
            //array_push($query,$_POST['fid']);
        $query = array($_POST['fid']);
//        }
        /*
        if($_POST['account']+0){
            $where .= " and account=? ";
            array_push($query,$_POST['account']);
        }password=? and */
        $sql = "select id as fid,account,dtype,mobile,dname from pft_member where dtype in (0,1,2,3) $where limit 1";
        $stmt =$connect->prepare($sql);
        $stmt->execute($query);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        $response = 111;
        if($row['fid']){
            $row['money'] = (int)simplexml_load_string($s->PFT_Member_Fund($row['fid']))->Rec->UUamoney;
            $response = $row;
            if($_POST['aid']+0>0){
                $response['credit'] = (int)simplexml_load_string($s->PFT_Member_Fund($row['fid'],1,$_POST['aid'])->Rec->UUkmoney);
                $response['credit'] += (int)simplexml_load_string($s->PFT_Member_Fund($row['fid'],2,$_POST['aid'])->Rec->UUbasecredit);
            }
        }
        response($response);
        break;

    //会员充值,消费
    case 'FundModify':
        if(!$_POST['fid'] || /*!$_POST['password'] ||*/
            ($_POST['modify']!='0' && $_POST['modify']!='1') ||
            $_POST['money']+0==0
        ) response(103);
        check_fx($_POST['fid']);
//        login($_POST['fid'],$_POST['password'],$connect);
        $response = array('status'=>'fail');
        $res = $s->PFT_Member_Fund_Modify($_POST['fid'],0,$_POST['money'],$_POST['modify'],0,null,3,0,'','API_user:'.$_POST['ac']);
        if($res == 100)
            $response = array('status'=>'success');
        response($response);
        break;

    //微信绑定
	case 'OpenChkBindStatus':
        if(!$_POST['openid']) response(103);
        $tousername = $_POST['appid']?$_POST['appId']:'wx6ebc34778c9326f6';
        $query = array($_POST['openid'],$tousername);
        if($_POST['fid']+0) {
            $where = 'and fid=? ';
            $query[] = $_POST['fid'];
        }
        $sql = "SELECT fid FROM uu_wx_member_pft WHERE fromusername=? AND tousername=? ";
        $sql .= $where." limit 1";
        $stmt =$connect->prepare($sql);
        $stmt->execute($query);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        $response = array('is_bind'=>0,'fid'=>'');
        if($row['fid']) $response = array('is_bind'=>1,'fid'=>$row['fid']);
        response($response);
        break;

    //发送短信验证码
    case 'SendVcode':
        if(!ismobile($_POST['mobile'])) response(103);
        $mobile = $_POST['mobile'];
        $sms_tpl_file = '/var/www/html/new/d/tpl/sms/register.txt';
        if(file_exists($sms_tpl_file)) {
            $tpl = file_get_contents($sms_tpl_file);
        }
        else {
            $response = 143;
            response($response);
            break;
        }

        $r = MemberAccount::SendVerifyCode($mobile, $tpl, $s, true);
        if ($r==100) {
            $response = array('status'=>'success');
        } elseif ($r==-1) {
            $response = 141;
        } else {
            $response = 142;
        }
        response($response);
        break;

    //注册
    case 'Register':
        if(!ismobile($_POST['mobile'])||
           !$_POST['dname'] || !$_POST['vcode'] ||
           !$_POST['password'] || !$_POST['repeat_password']
        ) response(103);
        $mobile = $_POST['mobile'];//客户端需要先检查手机号格式
        $dname  = safetxt($_POST['dname']);
//        $dType  = 5;//分销商身份的散客
        $dType  = isset($_POST['dtype'])? intval($_POST['dtype']) : 5;
        $dtype_array = array('0'=>1,'1'=>1,'5'=>1);
        if(!$dtype_array[$dType])  response(154);
        $repwd  = md5($_POST['repeat_password']);
        $pwd    = md5($_POST['password']);//密码，客户端需先md5加密一次。
        $invId  = $_POST['invId']+0;
        //只有分销商能传邀请人
        if($invId && $dType!=1) response(153);
        if(isset($_POST['vcode']) && !$_POST['csj']){
            $code = MemberAccount::ChkVerifyCode($mobile, $_POST['vcode']);
            if ($code===-1 ) {
                $response = 151;
                response($response);
                break;
            } elseif($code===false) {
                $response = 152;
                response($response);
                break;
            }
        }
        require_once("/var/www/html/new/conf/le.je");
        $le=new go_sql();
        $le->connect();
        $mem = new MemberAccount($le,0,$s);
        $result = $mem->mobileRegister($mobile, $dType,$dname, $pwd, $invId, 2);
        $le->close();
        //注册成功后 如果有填邀请人 那么加入他的分销商
        if($result['status']=='ok' && $invId>0){
            $fid_account = $result['body'];
            $fid_account = explode('|',$fid_account);
            $sql = "insert into pft_member_relationship
            (son_id,             parent_id,   status,  ship_type,  son_id_type,rectime) values
            ({$fid_account[0]},  $invId,      0,       0,          0,          now())";
            $stmt =$connect->prepare($sql);
            $stmt->execute();
            $sql_1 = "INSERT INTO pft_product_sale_list(fid,              aid,  pids)
                         VALUES(                          {$fid_account[0]},$invId,'')";
            $stmt =$connect->prepare($sql_1);
            $stmt->execute();
            //$result['sql'] = $sql;
        }
        //注册接口成功时的返回值
//        return array(
//            'status'=>'ok',
//            'msg'   => $msg,
//            'body'  => mysql_insert_id().'|'.$params['account']
//        );
        $response = array('result'=>$result);
        file_put_contents(
            '/var/www/html/new/d/logs/api_user_api/log1.txt',
            "\n".json_encode($result)."\n".$sql_1,
            FILE_APPEND
        );
        response($response);
        break;
    //获取可销售的景区列表
    case 'Lands':
        login($_POST['fid'],$_POST['password'],$connect,false);
        $m = new Member($s, $_POST['fid']);
        $salePros = $m->salePros(); // 2000 个产品大概 0.6 - 0.8 s
        $response = array();
        foreach($salePros as $row){
            if(!isset($response[$row['lid']]))
                $response[$row['lid']] = array('lid'=>$row['lid'],'title'=>$row['title']);
        }
        response($response);
        break;
    //根据景区id获取可销售产品
    case 'Prods':
        $login = login($_POST['fid'],$_POST['password'],$connect,false);
        $m = new Member($s, $_POST['fid']);
        $prods    = array();
        $today    = date('Y-m-d',$_SERVER['REQUEST_TIME']);
        $landid   = $_POST['lid'] + 0;
        $salePros = $m->salePros($landid); // 2000 个产品大概 0.6 - 0.8 s
        $suppliers = abc777\Member::Supplier($_POST['fid']);
        $suppliers[$_POST['fid']] = $login['dname'];
        require_once("/var/www/html/new/conf/le.je");
        $le=new go_sql();
        $le->connect();
        // print_r($salePros);
        foreach($salePros as $row){
            if(!isset($suppliers[$row['sapply_did']])) continue;
            $ps = abc777\Product::Dynamic_Price_And_Storage($s, $login['account'], $row['pid'], $row['sapply_did'], $today);
            if($ps['js']['p']==-1) continue;

//            $ro = array();
//            if($_POST['lid'] > 0 ){
                $sql = "select rst_type,rst_switch,rst_condition,daily_buy_limit,buy_interval,buy_num_limit from pft_prod_restrict
                    where pid={$row['pid']} and dstatus=0 limit 1";
                $GLOBALS['le']->query($sql);
                $ro=$GLOBALS['le']->fetch_assoc();
                if(!$ro) continue;
//            }
            $response[] = array(
                'pid' => $row['pid'],
                'sapply_did' => $row['sapply_did'],
                'dname' => $suppliers[$row['sapply_did']],
                'ttitle' => $row['ttitle'],
                'ltitle' => $row['title'],
                'js' => $ps['js']['p'],//结算价
                'ls' => $ps['ls']['p'],//零售价
                'lid' => $row['lid'],
                'tid' => $row['tid'],
                'effective'=> _htmlValid($row),
                'delaydays' => $row['delaydays'],//几天内有效
                'delaytype' => $row['delaytype'],//0 游玩日期(含)后开始计算  1 下单日期后开始计算
                'order_start' => $row['order_start'],//有效期开始日期
                'order_end' => $row['order_end'],//有效期截止日期
                //以下是从销售渠道配置表里取的
                'rst_type' =>$ro['rst_type'],/*限制类型，例如：1 会员卡购买 2 分销联盟购买 3 微信购买  4 会员卡*/
                'rst_switch' =>$ro['rst_switch'],/*购买开关 0 不可购买 1 可购买*/
                'rst_condition' =>$ro['rst_condition'],/*限制条件，例如：1.会员卡可以以卡号限制  2.联盟以积分梯度限制 */
                'daily_buy_limit' =>$ro['daily_buy_limit'],/*单日购买次数 -1 不限制*/
                'buy_interval' =>$ro['buy_interval'],/*购买间隔（分） -1 不限*/
                'buy_num_limit' =>$ro['buy_num_limit'],/*单次购买数量 -1 不限 */

            );
        }
        $le->close();
        response($response);
        break;
    //获取销售城市
    case 'SaleCity':
        login($_POST['fid'],$_POST['password'],$connect,false);
        require_once("/var/www/html/new/conf/le.je");
        $le=new go_sql();
        $le->connect();
        $response = array();
        $salePros = salePros(array('fields'=>array('l.area')));
        if(count($salePros)){
            include '/var/www/html/new/d/common/area.inc.php';
            foreach($salePros as $row){
                if($row['area']=='') continue;
                $area_a = explode('|', $row['area']);
                if(isset($areas[$area_a[1]])) $response[$area_a[1]] = $areas[$area_a[1]];
            }
        }
        response($response);
        break;

    //获取会员的分销商信息
    case 'GetPartner':
        //允许查询的供应商
        $array_16u = array('4'=>1,'55'=>1);
        if(!$array_16u[$_POST['fid']]) response(103);
        $login = login($_POST['fid'],$_POST['password'],$connect,false);
        $offset = ($_POST['page']+0) >0 ? ($_POST['page']-1)*100 : '0';
        $sql = "select son_id from pft_member_relationship where status=0 and parent_id={$login['fid']} and ship_type=0 and son_id!={$login['fid']} limit $offset,100";
        $stmt =$connect->prepare($sql);
        $stmt->execute();
        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
            $fid .= $row['son_id'].',';
        }
        $fid = rtrim($fid,',');
//        echo $fid;exit;
        $sql = "select card_no,memberID from pft_member_card where memberID in($fid) limit 100";
        $stmt =$connect->prepare($sql);
        $stmt->execute();
        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
            $card[$row['memberID']] = $row['card_no'];
        }
        $sql = "select  dname,account,mobile,m.id as fid,dtype,sex,id_card_no
                from pft_member m left join pft_member_extinfo e  on m.id=e.fid
                where m.id in($fid) limit 100";
        $stmt =$connect->prepare($sql);
        $stmt->execute();
        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
            $row['card_no'] = $card[$row['fid']];
            $response[] = $row;
        }
        response($response);
        break;

    //获取会员的交易记录
    case 'Trecord':
        if(!($_POST['fid']+0))  response(103);
        check_fx($_POST['fid']);
        $offset = ($_POST['page']+0) >0 ? $_POST['page']-1 : '0';
        $sql = "select dmoney as amount,daction as type,rectime as date,orderid,'' as pid,'' as title from pft_member_journal where fid=? order by id desc limit $offset,200";
        $stmt =$connect->prepare($sql);
        $stmt->execute(array($_POST['fid']));
        $response =  $stmt->fetchAll(\PDO::FETCH_ASSOC);
        foreach($response as $k => $v){
            if($v['type']==2) $response[$k]['type'] == 1;
            if($v['orderid']!=''){
                $x = simplexml_load_string($s->Order_Globle_Search( "","", "", "", "", "", "", "", "", "", "", "", $row['orderid'], "", "", "", "", "", "", "", "0", "1"));
                $response[$k]['pid'] = (int)$x->Rec->UUpid;
                $response[$k]['title'] = (string)$x->Rec->UUltitle;
            }

        }
        response($response);
        break;
    //获取会员的供应商信息
    case 'GetPartner_up':
        //允许查询的供应商
        $array_16u = array('4'=>1,'55'=>1);
        if(!$array_16u[$_POST['fid']]) response(103);
        $login = login($_POST['fid'],$_POST['password'],$connect);
        $offset = ($_POST['page']+0) >0 ? ($_POST['page']-1)*100 : '0';
        $sql = "select dname,account,mobile,m.id as fid,m.dtype
                from pft_member_relationship r left join pft_member m on m.id=parent_id
                where m.status in (0,3) and r.status=0 and son_id={$login['fid']} and ship_type=0 and length(m.account)=6 and parent_id!={$login['fid']} limit $offset,100";
        $stmt =$connect->prepare($sql);
        $stmt->execute(array($fid,md5($password)));
        $response = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        response($response);
        break;
    //挂失会员卡
    case 'Loss':
        if(!$_POST['card_no']) response(103);
        $card_no = trim($_POST['card_no']);
        $sql = "UPDATE pft_member_card SET status=1 WHERE card_no=? LIMIT 1";
        $stmt =$connect->prepare($sql);
        $ret = $stmt->execute(array($card_no));
        $response = array('status'=>'fail');
        if ($ret){
            $response = array('status'=>'success');
        }
        response($response);
        break;
    //根据会员卡卡号查询会员的名字 照片 身份证
    case 'CardInformation':
        if(!$_POST['card_no']) response(103);//member_card
        $card_no = trim($_POST['card_no']);
        $sql = "select dname,headphoto,id_card_no from pft_member m left join pft_member_extinfo e on m.id=e.fid left join pft_member_card a on m.id=a.memberID where a.card_no=? limit 1";
        $stmt =$connect->prepare($sql);
        $ret = $stmt->execute(array($card_no));
        $response = array('status'=>'fail');
        if ($ret){
            $response = $stmt->fetch(\PDO::FETCH_ASSOC);
        }
        response($response);
        break;
    //模仿登录--帐号密码确认
    case 'Login':
        if(!$_POST['account'] || !$_POST['password']) response(103);
        $sql = "select id as fid from pft_member where account=? and password=md5(?) limit 1";
        $stmt =$connect->prepare($sql);
        $stmt->execute(array($_POST['account'],$_POST['password']));
        $response = $stmt->fetch(\PDO::FETCH_ASSOC);
        if(!$response){
            $sql = "select id as fid from pft_member where mobile=? and password=md5(?) limit 1";
            $stmt =$connect->prepare($sql);
            $stmt->execute(array($_POST['account'],$_POST['password']));
            $response = $stmt->fetch(\PDO::FETCH_ASSOC);
            if(!$response){
                response(111);
            }
        }
        response($response);
        break;
    //获取店铺可以领取的优惠券列表
    case 'ShopCoupons':
        $data = $coupon->shop_coupons();
        if (!$data) {
            response(205);
        }
        foreach($data as $k => $v){

        }
        response($data);
        break;
    //获取自己已领取的优惠券
    case 'CouponList':
        $coupon_status = intval($_GET['status']);
        $data = $coupon->lists($coupon_status);
        if (!$data) {
            response(204);
        }
        response($data);
        break;
    //领取优惠券
    case 'CollectCoupon':
        $coupon_id = intval($_POST['Coupon_id']);
        $data = $coupon->collect_coupon($coupon_id);
        $response['status'] = $data['code'] == 200 ? 'success':$data['msg'];
        response($response);
        break;
    //重置密码
    case 'ResetPassword':
        $code = MemberAccount::ChkVerifyCode($_POST['mobile'], $_POST['vcode']);
        if ($code===-1 ) {
            $response = 151;
            response($response);
            break;
        } elseif($code===false) {
            $response = 152;
            response($response);
            break;
        }
        $sql = "select id from pft_member where mobile=? limit 1";
        $stmt =$connect->prepare($sql);
        $stmt->execute(array($_POST['mobile']));
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        $_POST['fid'] = $row['id'];
        check_fx($_POST['fid']);
        if(strlen($_POST['password'])!=32) response(112);
        $sql = "select id from pft_member where id=? limit 1";
        $stmt =$connect->prepare($sql);
        $stmt->execute(array($_POST['fid']));
        if(!$stmt->fetch(\PDO::FETCH_ASSOC)){
            response(111);
        }
        $nps = md5($_POST['password']);
        $sql = "update pft_member set password='$nps' where id=? limit 1";
        $stmt =$connect->prepare($sql);
        $stmt->execute(array($_POST['fid']));
        if($stmt->execute(array($_POST['fid']))){
            response(array('status'=>'success'));
        }
        response(array('status'=>'fail'));
        break;
    default:
        response(104);
		break;
}
session_destroy();


function response($sth){
    Db::Close();
    unset($GLOBALS['connect']);

    //    ErrorCode:101;无授权，拒绝连接
    //    ErrorCode:102;传输数据类型出错
    //    ErrorCode:103;请求接口没有传入所有必须参数
    //    ErrorCode:104;无此接口
    //    ErrorCode:110;提交次数超过每日上限
    //    ErrorCode:111;请求参数不匹配
    //    ErrorCode:112;密码需要md5后再传过来
    //    ErrorCode:141;短信发送间隔低于120秒
    //    ErrorCode:142;短信发送失败
    //    ErrorCode:143;短信模版不存在
    //    ErrorCode:151;短信验证码已失效或不存在
    //    ErrorCode:152;短信验证码错误
    //    ErrorCode:153;传了邀请人id但是注册的会员类型不是分销商
    //    ErrorCode:154;注册的分销商类型错误 只能是0,1,5
    //    ErrorCode:203;目前还没可领取的优惠券
    //    ErrorCode:204;目前还没有领取到优惠券
    $return = array('code'=>'200','list'=>$sth);
    if($_POST['action']=='GetPartner'){
        if($_POST['fid']==55)
            $return['recordcount']=5664;
        if($_POST['fid']==4)
            $return['recordcount']=130;
    }
    if(is_numeric($sth)) $return = array('code'=>$sth);
    echo (base64_encode(json_encode($return)));
    exit;
}


//判断输入的id password是否匹配 不匹配直接退出
//只取 供应商 分销商 景区 合并景区 集团 员工 都不行
//$check 为false时 不检查密码是否正确
function login($fid,$password,$connect,$check=true){
    if((!$fid || !$password)&&$check==true) response(103);
    if(!$fid && $check==false) response(103);
    $where = '';
    $query = array($fid);
    if($check==true){
        $where = 'and password=?';
        $query[] = md5($password);
    }
    $sql = "select id as fid,dname,account,dtype from pft_member where id=? $where and dtype in (0,1,2,3)limit 1";
    $stmt =$connect->prepare($sql);
    $stmt->execute($query);
    $row = $stmt->fetch(\PDO::FETCH_ASSOC);
    if(!$row['fid'])
        response(111);
    return array(
        'fid'=>$row['fid'],
        'dname'=>$row['dname'],
        'account'=>$row['account'],
        'dtype'=>$row['dtype']
    );
}

//在这个接口里 只可以操作先行和三亚先行的供应商和分销商
function check_fx($fid){
    $u16 = '4,55';
    $array_16u_1 = explode(',',$u16);
    foreach($array_16u_1 as $v){
        $array_16u[$v]=1;
    }
   // $array_16u = array('4'=>1,'55'=>1);
    if($array_16u[$fid]) return true;
    $sql = "select parent_id from pft_member_relationship where son_id=? and status=0 and ship_type=0 and parent_id in ($u16) limit 1";
    $stmt = $GLOBALS['connect']->prepare($sql);
    $stmt->execute(array($fid));
    $row = $stmt->fetch(\PDO::FETCH_ASSOC);
    if($row['parent_id']) return true;
    $sql = "select parent_id from pft_member_relationship where parent_id=? and status=0 and ship_type=0 and son_id in ($u16) limit 1";
    $stmt = $GLOBALS['connect']->prepare($sql);
    $stmt->execute(array($fid));
    $row = $stmt->fetch(\PDO::FETCH_ASSOC);
    if($row['parent_id']) return true;
    response(111);
}


function _htmlValid($p_info){
    if($p_info['delaydays']>0){
        if($p_info['delaytype']==0) $valid = '游玩日期(含)'.$p_info['delaydays'].'天内有效';
        if($p_info['delaytype']==1) $valid = '下单日期(含)'.$p_info['delaydays'].'天内有效';
    }
    if($p_info['order_start']=='' && $p_info['delaydays'] == 0){
        $valid = '订单当天有效';
    }

    if($p_info['order_start']!='' && $p_info['order_end']!='' ){
        $valid = '有效日期从'.$p_info['order_start'].' 至 '.$p_info['order_end'];
    }elseif($p_info['order_start']=='' && $p_info['order_end']!=''){
        $valid = '截止'.$p_info['order_end'];
    }


    return $valid;
}


function salePros($condition = array()){

    $prods     = array();
    $memberSID = isset($condition['memberSID']) ? $condition['memberSID']:$_POST['fid'];

    if(isset($condition['SysFields'])){
        $fields = array('p.id as pid,p.apply_did,p.p_status,l.id as lid,l.p_type,l.jtype,l.areacode,l.title,getPY(l.title,1) as py,l.salerid,l.area,l.topic,l.px,l.runtime,l.taobao_support,l.imgpath,l.address,t.id as tid,t.pay,t.getaddr,t.title as ttitle,t.tprice,t.notes,t.buy_limit_low,t.ddays,t.delaydays,t.status,f.ass_station,f.tourist_info,f.mdays,f.mhour,f.rdays,t.order_end,t.order_start,t.delaytype,t.sync_status');
    }else{
        $fields = array('l.id as lid,t.id as tid,p.id as pid,p.apply_did,l.title as ltitle,t.title as ttitle');
        if(isset($condition['fields'])) $fields = array_merge($fields, $condition['fields']);
    }

    $sql = "select ".implode(',', $fields)." from uu_products p left join uu_land l on p.contact_id=l.id left join uu_jq_ticket t on p.id=t.pid left join uu_land_f f on f.pid=p.id";

    $order = isset($condition['orderby']) ? ' '.$condition['orderby']:'';

    // 条件刷选
    $p_status    = 0;
    $apply_limit = 1;
    if(isset($condition['p_status']))    $p_status    = $condition['p_status'];
    if(isset($condition['apply_limit'])) $apply_limit = $condition['apply_limit'];
    $where = "where p.p_status=$p_status and p.apply_limit=$apply_limit";

    if(isset($condition['lid'])) $where.=" and l.id={$condition['lid']} ";
    if(isset($condition['pid'])) $where.=" and p.id={$condition['pid']} ";
    if(isset($condition['tid'])) $where.=" and t.id={$condition['tid']} ";

    // 一手供应
    if(isset($condition['NoDirect']) && $condition['NoDirect']) goto Evolute;
    $sql_search = "select l.pids,l.aid from pft_product_sale_list l left join pft_member m on l.aid=m.id where l.fid=$memberSID and l.status=0 and m.status=0";
    $GLOBALS['le']->query($sql_search);
    while($row=$GLOBALS['le']->fetch_assoc()) $pids_a[$row['aid']] = $row['pids'] ? explode(',', $row['pids']):'';
    $pids_a[$memberSID] = array('A');
    $pids_a = array_filter($pids_a);
    $aids_a = array_keys($pids_a);// 获取一手供应商
    if(count($aids_a)){
        $aids_s  = implode(',', $aids_a);
        $where1  = $where." and p.apply_did in ($aids_s)";
        $sql_lv1 = "$sql $where1 $order";
        $GLOBALS['le']->query($sql_lv1);
        while($row=$GLOBALS['le']->fetch_assoc()){
            if($pids_a[$row['apply_did']][0]!='A' && !in_array($row['pid'], $pids_a[$row['apply_did']])) continue;
            $row['aid'] = 0;
            $row['lvl'] = 0;
            $row['active']     = 0;
            $row['sapply_did'] = $row['apply_did'];
            $prods[] = $row;
        }
    }

    // 转分销
    Evolute:
    if(isset($condition['NoEvolute']) && $condition['NoEvolute']) goto The_End;
    $str = "select id,pid,sid,active,lvl,status from pft_p_apply_evolute where fid=$memberSID and status=0 and sid<>sourceid and sourceid<>$memberSID";
    $GLOBALS['le']->query($str);
    while($row=$GLOBALS['le']->fetch_assoc()){
        $secondInfo[$row['pid'].'_'.$row['sid']] = $row;
        $secondPids[] = $row['pid'];
    }
    if(count($secondPids)){
        $proInfo    = array();
        $secondPids = implode(',', $secondPids);
        $where2 = $where." and p.id in ($secondPids) ";
        $str2   = "$sql $where2 $order";
        $GLOBALS['le']->query($str2);
        while($row=$GLOBALS['le']->fetch_assoc()) $proInfo[$row['pid']] = $row;
        foreach($secondInfo as $key=>$value){
            list($pid, $sapply_did) = explode('_', $key);
            if(!isset($proInfo[$pid])) continue;
            $row = $proInfo[$pid];
            $row['aid'] = $sapply_did;
            $row['lvl'] = $value['lvl'];
            $row['eid'] = $value['id'];
            $row['active']     = $value['active'];
            $row['estatus']    = $value['status'];
            $row['sapply_did'] = $sapply_did;
            $prods[] = $row;
        }
    }

    The_End:
    return $prods;
}